
//
//  ESUserDetailViewController.m
//  Eyeshot
//
//  Created by admin on 15/7/4.
//  Copyright (c) 2015年 eyeshot. All rights reserved.
//

#import "ESUserDetailViewController.h"
#import "ESTableHeaderView.h"
#import "ESTitleView.h"
#import "ESPhotoProfileModel.h"
#import "ESNewPhotoModel.h"
#import "ESPhotoTableViewCell.h"
#import "ESVideoModel.h"
#import "ESVideoTableViewCell.h"
#import "ESDuanzi.h"
#import "ESDuanziTableCell.h"
#define kHeaderViewHeight 70
#define kSectionHeaderHeight 30

#define kProfileUrl @"http://api.budejie.com/api/api_open.php?a=profile&appname=baisishequ&asid=7AD5815A-BC34-40CA-A9BE-C9DAC444BC95&c=user&client=iphone&device=ios%20%E8%AE%BE%E5%A4%87&jbk=0&mac=&market=&openudid=a3f29abd63d37c5476e06c24cad694f1182f25b2&sex=m&udid=&uid=15094607&userid=15133875&ver=3.6"
#define kCommentUrl @"http://api.budejie.com/api/api_open.php?a=mycomment&appname=baisishequ&asid=7AD5815A-BC34-40CA-A9BE-C9DAC444BC95&c=comment&client=iphone&device=ios%20%E8%AE%BE%E5%A4%87&jbk=0&lastcid=0&mac=&market=&openudid=a3f29abd63d37c5476e06c24cad694f1182f25b2&page=1&per=20&udid=&uid=15133875&ver=3.6&visiting=15094607"
#define kMyTopicUrl @"http://api.budejie.com/api/api_open.php?a=mytopic&appname=baisishequ&asid=7AD5815A-BC34-40CA-A9BE-C9DAC444BC95&c=topic&client=iphone&device=ios%20%E8%AE%BE%E5%A4%87&jbk=0&lastid=0&mac=&market=&openudid=a3f29abd63d37c5476e06c24cad694f1182f25b2&order_type=desc&sex=m&type=1&udid=&uid=15094607&ver=3.6&visit_uid=15133875"

@interface ESUserDetailViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic, weak) UITableView *tableView;
@property (nonatomic, weak) UIImageView *expandZoomImageView;
@property (nonatomic, weak) ESTableHeaderView *headerV;
@property (nonatomic, weak) UIView *middleView;//显示帖子数和如何排序的view(区头)
@property (nonatomic, strong) ESPhotoProfileModel *profileModel;//用户信息的model;
@property (nonatomic, weak) UILabel *totalCardLabel;//显示帖子的数量
@property (nonatomic, strong) NSMutableArray *topicModelArr;//存放帖子的模型数组
@property (nonatomic, strong) NSMutableArray *commentModelArr;//存放评论的模型数组
@property (nonatomic, assign) BOOL isClick;
@end

static CGFloat kImageOriginHeight = 200;
static CGFloat kTempHeight = 0;

@implementation ESUserDetailViewController


- (void)requestProfileData
{
    NSString *userid = self.userid;
    NSString *reqStr = @"http://api.budejie.com/api/api_open.php";
    NSDictionary *reqParas = @{@"a": @"profile",
                               @"appname": @"baisishequ",
                               @"asid": @"7AD5815A-BC34-40CA-A9BE-C9DAC444BC95",
                               @"c": @"user",
                               @"client": @"iphone",
                               @"device": @"ios%20%E8%AE%BE%E5%A4%87",
                               @"jbk": @"0",
                               @"mac": @"",
                               @"market": @"",
                               @"openudid": @"a3f29abd63d37c5476e06c24cad694f1182f25b2",
                               @"sex": @"m",
                               @"udid": @"",
                               @"uid":@"15094607",
                               @"userid": userid,
                               @"ver": @"3.6"
                               };
    
    AFHTTPRequestOperationManager *requestManager = [AFHTTPRequestOperationManager manager];
    [requestManager GET:reqStr parameters:reqParas success:^(AFHTTPRequestOperation *operation, NSDictionary *dict) {
    
        NSDictionary *dict1 = dict[@"data"];
        ESPhotoProfileModel *profileModel = [[ESPhotoProfileModel alloc] init];
        self.profileModel = profileModel;
        [profileModel setValuesForKeysWithDictionary:dict1];
        //设置上部背景图
        [self.expandZoomImageView sd_setImageWithURL:[NSURL URLWithString:profileModel.background_image]];
            
        //给自定义的表头赋值
         [self createTabelViewHeader];
        self.headerV.profileModel = self.profileModel;
        
        //设置bar上得title
        ESTitleView *view = [[ESTitleView alloc] init];
        [view setTitle:self.profileModel.username forState:(UIControlStateNormal)];
        [view setTitleFontSize:15];
        self.navigationItem.titleView = view;
       
            
        [self.tableView reloadData];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        ESLog(@"%@",error);
    }];
}


- (void)requestTopicData
{
    NSString *userid = self.userid;
    NSString *reqStr = @"http://api.budejie.com/api/api_open.php";
    NSDictionary *reqParas = @{@"a": @"mytopic",
                               @"appname": @"baisishequ",
                               @"asid": @"7AD5815A-BC34-40CA-A9BE-C9DAC444BC95",
                               @"c": @"topic",
                               @"client": @"iphone",
                               @"device": @"ios%20%E8%AE%BE%E5%A4%87",
                               @"jbk": @"0",
                               @"mac": @"",
                               @"market": @"",
                               @"openudid": @"a3f29abd63d37c5476e06c24cad694f1182f25b2",
                               @"order_type":@"desc",
                               @"sex": @"m",
                               @"type":@1,
                               @"udid": @"",
                               @"uid":@"15094607",
                               @"ver":@"3.6",
                               @"visit_uid":userid
                               };
    
    AFHTTPRequestOperationManager *requestManager = [AFHTTPRequestOperationManager manager];
    [requestManager GET:reqStr parameters:reqParas success:^(AFHTTPRequestOperation *operation, NSDictionary *dict) {
        
       NSArray *arr1 = dict[@"topics"];
        
        for (NSDictionary *dic in arr1)
        {
            if ([(dic[@"cdn_img"]) isEqualToString:@""] || (dic[@"cdn_img"]) == nil)
            {
                ESDuanzi *model = [[ESDuanzi alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                 [self.topicModelArr addObject:model];
            }else if ([(dic[@"videouri"]) isEqualToString:@""] && (![(dic[@"cdn_img"]) isEqualToString:@""] && (dic[@"cdn_img"]) != nil))
            {
                ESNewPhotoModel *model = [[ESNewPhotoModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                 [self.topicModelArr addObject:model];
                
            }else
            {
                ESVideoModel *model = [[ESVideoModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [self.topicModelArr addObject:model];
            }
           
           
        }
        
        
        [self.tableView reloadData];
        
//        NSIndexSet *indexSet = [[NSIndexSet alloc] initWithIndex:0];
//        [self.tableView reloadSections:indexSet withRowAnimation:NO];
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        ESLog(@"%@",error);
    }];
}

//没有用到
- (void)requestCommentData
{
    NSString *userid = self.userid;
    NSString *reqStr = @"http://api.budejie.com/api/api_open.php";
    NSDictionary *reqParas = @{@"a": @"mycomment",
                               @"appname": @"baisishequ",
                               @"asid": @"7AD5815A-BC34-40CA-A9BE-C9DAC444BC95",
                               @"c": @"comment",
                               @"client": @"iphone",
                               @"device": @"ios%20%E8%AE%BE%E5%A4%87",
                               @"jbk": @"0",
                               @"lastcid":@"0",
                               @"mac": @"",
                               @"market": @"",
                               @"openudid": @"a3f29abd63d37c5476e06c24cad694f1182f25b2",
                               @"page":@"1",
                               @"per":@20,
                               @"udid": @"",
                               @"uid":userid,
                               @"ver":@"3.6",
                               @"visiting":@"15094607"
                               };
    
    AFHTTPRequestOperationManager *requestManager = [AFHTTPRequestOperationManager manager];
    [requestManager GET:reqStr parameters:reqParas success:^(AFHTTPRequestOperation *operation, NSDictionary *dict) {
        
        NSArray *arr1 = dict[@"topics"];
        
        for (NSDictionary *dic in arr1)
        {
            if ([(dic[@"cdn_img"]) isEqualToString:@""] || (dic[@"cdn_img"]) == nil)
            {
                ESDuanzi *model = [[ESDuanzi alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [self.commentModelArr addObject:model];
            }else if ([(dic[@"videouri"]) isEqualToString:@""] && (![(dic[@"cdn_img"]) isEqualToString:@""] && (dic[@"cdn_img"]) != nil))
            {
                ESNewPhotoModel *model = [[ESNewPhotoModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [self.commentModelArr addObject:model];
                
            }else
            {
                ESVideoModel *model = [[ESVideoModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [self.commentModelArr addObject:model];
            }
            
            
        }
        
        
        [self.tableView reloadData];
        
        //        NSIndexSet *indexSet = [[NSIndexSet alloc] initWithIndex:0];
        //        [self.tableView reloadSections:indexSet withRowAnimation:NO];
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        ESLog(@"%@",error);
    }];
}






- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.topicModelArr = [[NSMutableArray alloc] initWithCapacity:0];
    
    self.commentModelArr = [[NSMutableArray alloc] initWithCapacity:0];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"Profile_reportIcon"] imageWithRenderingMode:(UIImageRenderingModeAlwaysOriginal)] style:(UIBarButtonItemStylePlain) target:self action:@selector(showFunctionView)];
    
    
    
//    ESTitleView *view = [[ESTitleView alloc] init];
//    [view setTitle:self.profileModel.username forState:(UIControlStateNormal)];
//    self.navigationItem.titleView = view;
    
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, kScreenH - BAR_HEIGHT) style:(UITableViewStyleGrouped)];
    
    self.tableView = tableView;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    //创建上方的大图
    self.tableView.contentInset = UIEdgeInsetsMake(kImageOriginHeight, 0, 0, 0);
     UIImageView *expandZoomImageView = [[UIImageView alloc] init];
    self.expandZoomImageView = expandZoomImageView;

    self.expandZoomImageView.frame = CGRectMake(0, -kImageOriginHeight - kTempHeight, self.tableView.width, kImageOriginHeight + kTempHeight);
    [self.view addSubview:self.tableView];
    [self.tableView addSubview:self.expandZoomImageView];
    
    //创建headerView
//    [self createTabelViewHeader];
    
    //请求
    [self requestProfileData];
    //请求帖子数据
    [self requestTopicData];
}

//显示功能框
- (void)showFunctionView
{
    UIAlertController *alertV = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:(UIAlertControllerStyleActionSheet)];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"帖子筛选" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction *action) {
        
    }];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"举报" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction *action) {
        
    }];
    
    UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction *action) {
        
    }];
    
    [alertV addAction:action1];
    [alertV addAction:action2];
    [alertV addAction:action3];
    
    [self presentViewController:alertV animated:YES completion:^{
        
    }];
    
    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (_isClick == YES)
    {
        _isClick = NO;
        return 0;
    }
    return kSectionHeaderHeight;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, kSectionHeaderHeight)];
    self.middleView = view;
//    view.backgroundColor = [UIColor grayColor];
    UILabel *totalCardLabel = [[UILabel alloc] initWithFrame:CGRectMake(kHorizen * 4, 5, (kScreenW - kHorizen *8)/2, kSectionHeaderHeight - 10)];
    totalCardLabel.font = [UIFont systemFontOfSize:12];
    totalCardLabel.textColor = [UIColor blackColor];
    totalCardLabel.backgroundColor = [UIColor whiteColor];
     self.totalCardLabel = totalCardLabel;
     self.totalCardLabel.text = [NSString stringWithFormat:@"共%@帖子",self.profileModel.tiezi_count];
    [view addSubview:totalCardLabel];
    
    UIButton *sortButton = [[UIButton alloc] initWithFrame:CGRectMake(kScreenW - 70, 5, 50, kSectionHeaderHeight - 10)];
    [sortButton addTarget:self action:@selector(sortBtn:) forControlEvents:(UIControlEventTouchUpInside)];
    sortButton.backgroundColor = [UIColor whiteColor];
    [view addSubview:sortButton];
    return view;
    
}


//中间的view中的评论排序
- (void)sortBtn:(UIButton *)btn
{
//    NSLog(@"按什么排序");
}


//自定义一个表头
- (void)createTabelViewHeader
{
    //为了让控件能覆盖上面的大图
    UIView *viewAdd = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, [ESTableHeaderView heightForHeaderViewWithModel:self.profileModel])];
    viewAdd.backgroundColor = [UIColor cyanColor];
    self.tableView.tableHeaderView = viewAdd;
    
    
    ESTableHeaderView *headerV = [[ESTableHeaderView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, [ESTableHeaderView heightForHeaderViewWithModel:self.profileModel])];

    self.headerV = headerV;
    headerV.backgroundColor = [UIColor whiteColor];
    [self.tableView addSubview:headerV];
    
    //控件的事件
    [headerV.headPhotoBtn addTarget:self action:@selector(intoUserBigPhoto) forControlEvents:(UIControlEventTouchUpInside)];
    [headerV.cardBtn addTarget:self action:@selector(showUserCells) forControlEvents:(UIControlEventTouchUpInside)];
    [headerV.commentBtn addTarget:self action:@selector(showCommentCells) forControlEvents:(UIControlEventTouchUpInside)];
    
}

//显示用户大头像
- (void)intoUserBigPhoto
{
    NSLog(@"intoUserBigPhoto");
}
//让下面的cell显示用户自己发的帖子
- (void)showUserCells
{
    _isClick = NO;
 
    NSIndexSet *indexSet=[[NSIndexSet alloc] initWithIndex:0];
    [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
    [self.tableView bringSubviewToFront:self.headerV];

    NSLog(@"showUserCells");
    
}
//让下面的cell显示用户评论过的帖子
- (void)showCommentCells
{
    NSLog(@"showCommentCells");
    _isClick = YES;
    
    NSIndexSet *indexSet=[[NSIndexSet alloc] initWithIndex:0];
    [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
    [self.tableView bringSubviewToFront:self.headerV];
}




#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return self.topicModelArr.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  
     id model = [self.topicModelArr objectAtIndex:indexPath.row];
    
    if ([model isMemberOfClass:[ESDuanzi class]])
    {
        static NSString *IDDuan = @"userDCDuanzi";
        ESDuanziTableCell *cell = [tableView dequeueReusableCellWithIdentifier:IDDuan];
        if (!cell) {
            cell = [[ESDuanziTableCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:IDDuan];
        }
        
        [cell setModel:model];
        
        return cell;

    }else if ([model isMemberOfClass:[ESNewPhotoModel class]])
    {
        static NSString *IDPhoto = @"userDCPhoto";
        ESPhotoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:IDPhoto];
        if (!cell) {
            cell = [[ESPhotoTableViewCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:IDPhoto];
        }
        
        [cell setPhotoModel:model];
        
        return cell;
    }else
    {
        static NSString *IDVedio = @"userDCVedio";
        ESVideoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:IDVedio];
        if (!cell) {
            cell = [[ESVideoTableViewCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:IDVedio];
        }
        
        [cell setModel:model];
        
        return cell;

    }
    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    id model = [self.topicModelArr objectAtIndex:indexPath.row];
    
    if ([model isMemberOfClass:[ESDuanzi class]])
    {
       return  [ESDuanziTableCell heightForCellWithModel:model];
        
    }else if ([model isMemberOfClass:[ESNewPhotoModel class]])
    {
       return  [ESPhotoTableViewCell heightForCellWithModel:model];
        
    }else
    {
       return  [ESVideoTableViewCell getHeightForCellByModel:model];
        
    }

    
//     ESNewPhotoModel *model = [self.topicModelArr objectAtIndex:indexPath.row];
//    return [ESPhotoTableViewCell heightForCellWithModel:model];

}

//上方大图的变大事件
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat yOffset = scrollView.contentOffset.y;
//    NSLog(@"%f",yOffset);
    CGFloat xOffset = (yOffset + kImageOriginHeight)/2;
    if (yOffset < -kImageOriginHeight)
    {
        CGRect f = self.expandZoomImageView.frame;
        f.origin.y = yOffset - kTempHeight;
        f.size.height = -yOffset + kTempHeight;
        f.origin.x = xOffset;
        f.size.width = kScreenW + fabs(xOffset) * 2;
        self.expandZoomImageView.frame = f;
    }
}

@end
